import odoo from '@/odooapi'

const Model = odoo.env('mail.channel')

const state = {
  isInited: false,
  channel: {},
  messages: [],
  first_message_id: 0,
  isScroll: 1
}

const mutations = {
  SET_IsInited: (state, value) => {
    state.isInited = value
  },
  SET_CHANNEL: (state, row) => {
    state.channel = row
  },

  UPDATE_CHANNEL: (state, row) => {
    state.channel = { ...state.channel, ...row }
  },

  SET_FIRST: (state, first_message_id) => {
    state.first_message_id = first_message_id
  },
  SET_MESSAGE: (state, messages) => {
    state.messages = messages
  },
  SET_SCROLL: (state, val) => {
    state.isScroll = val
  }
}

const actions = {
  async initChannel({ commit, state, dispatch }, channel_id) {
    if (!state.isInited) {
      const channel = await Model.browse_one(channel_id)
      commit('SET_CHANNEL', channel)

      const msgs = await Model.channel_fetch_message(channel_id)
      console.log('xxx, initChannel', msgs)
      if (msgs.length) {
        const first_message_id = msgs[msgs.length - 1].id
        commit('SET_FIRST', first_message_id)
      }

      commit('SET_SCROLL', 1)
      const msgs2 = msgs.reverse()
      commit('SET_MESSAGE', msgs2)
      // console.log('xxxxxx, init ', msgs2)
      commit('SET_IsInited', true)
    }

    // 取当前频道中的新消息
    const chn = odoo.bus.getMsg(channel_id)
    dispatch('messageGet', chn)
    // console.log('xxxxxx, init22222 ', chn)

    // 消息请求的回调函数
    const poll_callback = chn => {
      dispatch('messageGet', chn)
    }

    // 设置 回调函数, 启动消息查询
    odoo.bus.setCallback(channel_id, poll_callback)
    odoo.bus.startPoll()

    return new Promise(resolve => {
      resolve()
    })
  },

  async fetchHistory({ commit, state, dispatch }) {
    console.log('xxx, fetchHistory')
    const msgs = await Model.channel_fetch_message(
      state.channel.id,
      state.first_message_id
    )
    console.log('xxx, fetchHistory', msgs)
    if (msgs.length) {
      const first_message_id = msgs[msgs.length - 1].id
      commit('SET_FIRST', first_message_id)
    }

    const msgs2 = msgs.reverse()
    commit('SET_SCROLL', 0)
    commit('SET_MESSAGE', [...msgs2, ...state.messages])

    // this.messages.unshift(...msgs2)

    return new Promise(resolve => {
      resolve(state.messages)
    })
  },

  async messageGet({ commit, state, dispatch }, chn) {
    chn.partner_ids.forEach(item => {
      if (item.id === state.channel.partner_id) {
        commit('UPDATE_CHANNEL', {
          is_typing: item.is_typing,
          last_message_id: item.last_message_id
        })
      }

      dispatch('updateMessage', chn.messages)
    })

    return new Promise(resolve => {
      resolve()
    })
  },

  async updateMessage({ commit, state, dispatch }, messages) {
    commit('SET_SCROLL', 1)

    messages.forEach(rec => {
      // this.messages = this.updateOrInsert(this.messages, item)
      const list = state.messages
      const dest = list.filter(item => item.id === rec.id)

      if (!dest.length) {
        commit('SET_MESSAGE', [...list, rec])
      } else {
        const element = dest[0]
        Object.keys(rec).forEach(item => {
          element[item] = rec[item]
        })
        commit('SET_MESSAGE', [...list])
      }
    })

    return new Promise(resolve => {
      resolve()
    })
  },

  async postNotifyTyping({ commit, state, dispatch }, is_typing) {
    await Model.notify_typing(state.channel.id, is_typing)
    return new Promise(resolve => {
      resolve()
    })
  },

  async postMessage({ commit, state, dispatch }, msg) {
    await Model.private_message_post(state.channel.id, msg)

    return new Promise(resolve => {
      resolve()
    })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
